//
//  WBMainViewController.swift
//  Weibo
//
//  Created by 夏灵烽 on 2025/1/1.
//

import UIKit

class WBMainViewController: UITabBarController {

    // MARK: - 属性
    private  lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    // MARK: - 系统方法
    // MARK: - 加载视图
    override func viewDidLoad() {
        super.viewDidLoad()
                
        setupTabbarInfo()
        
        setupChildControllers()
        
        setupComposeButton()
    }
    
    // MARK: - 设置竖屏
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask
    {
        get {
            return .portrait
        }
    }
    
    // MARK: - 自定义方法
    // MARK: - 设置tabbar背景
    func setupTabbarInfo() {
        tabBar.isTranslucent = false
        
        let appearance = UITabBarAppearance()
        
        appearance.backgroundColor = UIColor.cz_color(withHex: 0xF6F6F6)
        appearance.configureWithOpaqueBackground()

        tabBar.standardAppearance = appearance
        
        if #available(iOS 15.0, *) {
            tabBar.scrollEdgeAppearance = appearance
        } else {
            tabBar.backgroundColor = UIColor.cz_color(withHex: 0xF6F6F6)
        }
    }
    
    // MARK: - 添加中间加号按钮
    private func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(viewControllers?.count ?? 1)
        
        let width = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * width, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeClick), for: .touchUpInside)
    }
    
    @objc private func composeClick() {
        
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        vc.title = "test"
        
        let nav = UINavigationController(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
        
        present(nav, animated: true, completion: nil)
    }
    
    // MARK: - 设置tabbarcontroller的子控制器
    private func setupChildControllers() {
        
        // 配置信息字典
        var infoArr = [[String: AnyObject]]()
        
        // 获取文档目录 URL
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        
        var fileURL: URL
        
        // 附加文件名
        if #available(iOS 16.0, *) {
            fileURL = documentsURL.appending(path: "main.json", directoryHint: .notDirectory)
        } else {
            fileURL = documentsURL.appendingPathComponent("main.json")
        }
        
        do {
            let data = try Data(contentsOf: fileURL)
            let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
            infoArr = jsonObject as? [[String: AnyObject]] ?? []
        } catch  {
            print(error)
        }
        
        if infoArr.count <= 0  {
            let path: String = Bundle.main.path(forResource: "main.json", ofType: nil) ?? ""
            
            var url: URL
            if #available(iOS 16.0, *) {
                url = URL(filePath: path)
            } else {
                url = URL(fileURLWithPath: path)
            }

            do {
                let data = try Data(contentsOf: url)
                let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
                infoArr = jsonObject as? [[String: AnyObject]] ?? []
            } catch  {
                print(error)
            }
        }
        
        var vcArr = [UIViewController]()
        for dict in infoArr {
            vcArr.append(controller(dict: dict))
        }
        
        viewControllers = vcArr
    }
    
    
    private func controller(dict: [String: AnyObject]) -> UIViewController
    {
        guard let clsName = dict["clsName"] as? String,
              let title = dict["title"]  as? String,
              let imageName = dict["imageNmae"]  as? String,
              let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
              let visitorDict = dict["visitorInfo"] as? [String: String]
                
        else {
            return UIViewController()
        }
        
        let vc = cls.init()
        vc.title = title
        vc.visitorInfoDict = visitorDict
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)], for: .normal)
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
    
}
